<template>
  <el-dialog
    v-model="dialogVisible"
    title="版本管理"
    width="1000px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <div class="version-management">
      <!-- 当前版本信息 -->
      <el-card class="current-version-card" shadow="never">
        <template #header>
          <div class="card-header">
            <span class="card-title">当前版本</span>
            <div class="header-actions">
              <el-button type="primary" size="small" @click="handleCreateVersion">
                <el-icon><Plus /></el-icon>
                创建新版本
              </el-button>
            </div>
          </div>
        </template>
        
        <div class="current-version-info">
          <el-row :gutter="20">
            <el-col :span="8">
              <div class="version-item">
                <label>版本号：</label>
                <span class="version-number">{{ systemData.version }}</span>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="version-item">
                <label>状态：</label>
                <el-tag :type="getStatusTagType(systemData.status)" size="small">
                  {{ getStatusText(systemData.status) }}
                </el-tag>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="version-item">
                <label>创建时间：</label>
                <span>{{ systemData.createTime }}</span>
              </div>
            </el-col>
          </el-row>
          <div class="version-description">
            <label>版本说明：</label>
            <p>{{ systemData.description || '暂无说明' }}</p>
          </div>
        </div>
      </el-card>

      <!-- 版本历史列表 -->
      <el-card class="version-history-card" shadow="never">
        <template #header>
          <div class="card-header">
            <span class="card-title">版本历史</span>
            <div class="header-actions">
              <el-button size="small" @click="handleRefresh">
                <el-icon><Refresh /></el-icon>
                刷新
              </el-button>
              <el-button size="small" @click="handleExportHistory">
                <el-icon><Download /></el-icon>
                导出历史
              </el-button>
            </div>
          </div>
        </template>

        <el-table
          :data="versionHistory"
          style="width: 100%"
          v-loading="loading"
        >
          <el-table-column prop="version" label="版本号" width="120">
            <template #default="{ row }">
              <span class="version-number">{{ row.version }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" width="100">
            <template #default="{ row }">
              <el-tag :type="getStatusTagType(row.status)" size="small">
                {{ getStatusText(row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="description" label="版本说明" show-overflow-tooltip />
          <el-table-column prop="creator" label="创建人" width="100" />
          <el-table-column prop="createTime" label="创建时间" width="160" />
          <el-table-column prop="publishTime" label="发布时间" width="160">
            <template #default="{ row }">
              <span>{{ row.publishTime || '未发布' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="250" fixed="right">
            <template #default="{ row }">
              <el-button type="primary" size="small" link @click="handleViewVersion(row)">
                查看
              </el-button>
              <el-button type="success" size="small" link @click="handleCompareVersion(row)">
                对比
              </el-button>
              <el-button
                type="warning"
                size="small"
                link
                @click="handleRestoreVersion(row)"
                :disabled="row.status === 'active'"
              >
                恢复
              </el-button>
              <el-button
                type="danger"
                size="small"
                link
                @click="handleDeleteVersion(row)"
                :disabled="row.status === 'active'"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>

    <!-- 创建版本对话框 -->
    <el-dialog
      v-model="createVersionVisible"
      title="创建新版本"
      width="600px"
      :close-on-click-modal="false"
      append-to-body
    >
      <el-form
        ref="versionFormRef"
        :model="versionForm"
        :rules="versionFormRules"
        label-width="100px"
      >
        <el-form-item label="版本号" prop="version">
          <el-input
            v-model="versionForm.version"
            placeholder="请输入版本号，如：V2.1"
            maxlength="20"
          />
        </el-form-item>
        <el-form-item label="版本类型" prop="type">
          <el-select v-model="versionForm.type" placeholder="请选择版本类型" style="width: 100%">
            <el-option label="主要版本" value="major" />
            <el-option label="次要版本" value="minor" />
            <el-option label="补丁版本" value="patch" />
          </el-select>
        </el-form-item>
        <el-form-item label="版本说明" prop="description">
          <el-input
            v-model="versionForm.description"
            type="textarea"
            :rows="4"
            placeholder="请输入版本更新说明"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="基于版本">
          <el-select v-model="versionForm.baseVersion" placeholder="请选择基于的版本" style="width: 100%">
            <el-option
              v-for="version in versionHistory"
              :key="version.id"
              :label="version.version"
              :value="version.version"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="立即发布">
          <el-switch v-model="versionForm.autoPublish" />
          <span class="form-tip">开启后新版本将立即生效</span>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="createVersionVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmitVersion">创建</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 版本详情对话框 -->
    <el-dialog
      v-model="versionDetailVisible"
      title="版本详情"
      width="800px"
      :close-on-click-modal="false"
      append-to-body
    >
      <div class="version-detail" v-if="currentVersionDetail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="版本号">
            {{ currentVersionDetail.version }}
          </el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="getStatusTagType(currentVersionDetail.status)" size="small">
              {{ getStatusText(currentVersionDetail.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="创建人">
            {{ currentVersionDetail.creator }}
          </el-descriptions-item>
          <el-descriptions-item label="创建时间">
            {{ currentVersionDetail.createTime }}
          </el-descriptions-item>
          <el-descriptions-item label="发布时间">
            {{ currentVersionDetail.publishTime || '未发布' }}
          </el-descriptions-item>
          <el-descriptions-item label="基于版本">
            {{ currentVersionDetail.baseVersion || '无' }}
          </el-descriptions-item>
          <el-descriptions-item label="版本说明" :span="2">
            {{ currentVersionDetail.description }}
          </el-descriptions-item>
        </el-descriptions>

        <div class="version-content" style="margin-top: 20px;">
          <h4>版本内容</h4>
          <div class="content-preview">
            {{ currentVersionDetail.content || '暂无内容' }}
          </div>
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="versionDetailVisible = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 版本对比对话框 -->
    <el-dialog
      v-model="compareVersionVisible"
      title="版本对比"
      width="1200px"
      :close-on-click-modal="false"
      append-to-body
    >
      <div class="version-compare">
        <div class="compare-header">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-select v-model="compareForm.sourceVersion" placeholder="选择源版本" style="width: 100%">
                <el-option
                  v-for="version in versionHistory"
                  :key="version.id"
                  :label="version.version"
                  :value="version.version"
                />
              </el-select>
            </el-col>
            <el-col :span="12">
              <el-select v-model="compareForm.targetVersion" placeholder="选择目标版本" style="width: 100%">
                <el-option
                  v-for="version in versionHistory"
                  :key="version.id"
                  :label="version.version"
                  :value="version.version"
                />
              </el-select>
            </el-col>
          </el-row>
        </div>

        <div class="compare-content" v-if="compareForm.sourceVersion && compareForm.targetVersion">
          <el-row :gutter="20">
            <el-col :span="12">
              <div class="compare-panel">
                <h4>{{ compareForm.sourceVersion }}</h4>
                <div class="content-diff">
                  <p>这里显示源版本的内容...</p>
                </div>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="compare-panel">
                <h4>{{ compareForm.targetVersion }}</h4>
                <div class="content-diff">
                  <p>这里显示目标版本的内容...</p>
                </div>
              </div>
            </el-col>
          </el-row>
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="compareVersionVisible = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">关闭</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Plus,
  Refresh,
  Download
} from '@element-plus/icons-vue'

// Props
interface Props {
  visible: boolean
  systemData?: any
}

const props = withDefaults(defineProps<Props>(), {
  systemData: () => ({})
})

// Emits
const emit = defineEmits(['update:visible', 'success'])

// 对话框显示状态
const dialogVisible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
})

// 加载状态
const loading = ref(false)

// 子对话框显示状态
const createVersionVisible = ref(false)
const versionDetailVisible = ref(false)
const compareVersionVisible = ref(false)

// 表单引用
const versionFormRef = ref()

// 版本表单数据
const versionForm = reactive({
  version: '',
  type: 'minor',
  description: '',
  baseVersion: '',
  autoPublish: false
})

// 版本表单验证规则
const versionFormRules = {
  version: [
    { required: true, message: '请输入版本号', trigger: 'blur' },
    { pattern: /^V\d+\.\d+(\.\d+)?$/, message: '版本号格式不正确，如：V1.0 或 V1.0.1', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择版本类型', trigger: 'change' }
  ],
  description: [
    { required: true, message: '请输入版本说明', trigger: 'blur' },
    { min: 10, max: 500, message: '版本说明长度在 10 到 500 个字符', trigger: 'blur' }
  ]
}

// 版本历史数据
const versionHistory = ref([
  {
    id: 1,
    version: 'V2.1',
    status: 'active',
    description: '更新安全检查流程，增加应急处理程序',
    creator: '张三',
    createTime: '2024-01-01 09:00:00',
    publishTime: '2024-01-01 10:00:00',
    baseVersion: 'V2.0',
    content: '详细的制度内容...'
  },
  {
    id: 2,
    version: 'V2.0',
    status: 'archived',
    description: '重构制度框架，优化管理流程',
    creator: '李四',
    createTime: '2023-06-01 14:30:00',
    publishTime: '2023-06-01 15:00:00',
    baseVersion: 'V1.0',
    content: '详细的制度内容...'
  },
  {
    id: 3,
    version: 'V1.0',
    status: 'archived',
    description: '初始版本',
    creator: '王五',
    createTime: '2023-01-01 08:00:00',
    publishTime: '2023-01-01 09:00:00',
    baseVersion: '',
    content: '详细的制度内容...'
  }
])

// 当前版本详情
const currentVersionDetail = ref({})

// 版本对比表单
const compareForm = reactive({
  sourceVersion: '',
  targetVersion: ''
})

// 获取状态标签类型
const getStatusTagType = (status: string) => {
  const types: Record<string, string> = {
    active: 'success',
    draft: 'info',
    expired: 'warning',
    abolished: 'danger',
    archived: ''
  }
  return types[status] || 'info'
}

// 获取状态文本
const getStatusText = (status: string) => {
  const texts: Record<string, string> = {
    active: '生效中',
    draft: '草稿',
    expired: '已过期',
    abolished: '已废止',
    archived: '已归档'
  }
  return texts[status] || status
}

// 刷新版本历史
const handleRefresh = () => {
  loading.value = true
  setTimeout(() => {
    loading.value = false
    ElMessage.success('刷新成功')
  }, 1000)
}

// 导出版本历史
const handleExportHistory = () => {
  ElMessage.success('版本历史导出成功')
}

// 创建新版本
const handleCreateVersion = () => {
  // 重置表单
  Object.assign(versionForm, {
    version: '',
    type: 'minor',
    description: '',
    baseVersion: props.systemData.version,
    autoPublish: false
  })
  createVersionVisible.value = true
}

// 提交新版本
const handleSubmitVersion = async () => {
  try {
    await versionFormRef.value.validate()
    
    // 模拟创建版本API
    await mockCreateVersion(versionForm)
    
    ElMessage.success('版本创建成功')
    createVersionVisible.value = false
    emit('success')
    handleRefresh()
  } catch (error) {
    console.error('创建版本失败:', error)
  }
}

// 查看版本
const handleViewVersion = (version: any) => {
  currentVersionDetail.value = version
  versionDetailVisible.value = true
}

// 对比版本
const handleCompareVersion = (version: any) => {
  compareForm.sourceVersion = version.version
  compareForm.targetVersion = props.systemData.version
  compareVersionVisible.value = true
}

// 恢复版本
const handleRestoreVersion = async (version: any) => {
  try {
    await ElMessageBox.confirm(
      `确认恢复到版本 ${version.version}？恢复后当前版本将被归档。`,
      '确认恢复版本'
    )
    
    // 模拟恢复版本API
    await mockRestoreVersion(version.id)
    
    ElMessage.success('版本恢复成功')
    emit('success')
    handleRefresh()
  } catch (error) {
    // 用户取消
  }
}

// 删除版本
const handleDeleteVersion = async (version: any) => {
  try {
    await ElMessageBox.confirm(
      `确认删除版本 ${version.version}？删除后无法恢复。`,
      '确认删除版本'
    )
    
    // 模拟删除版本API
    await mockDeleteVersion(version.id)
    
    ElMessage.success('版本删除成功')
    handleRefresh()
  } catch (error) {
    // 用户取消
  }
}

// 关闭对话框
const handleClose = () => {
  dialogVisible.value = false
}

// 模拟API函数
const mockCreateVersion = (data: any) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      console.log('创建版本:', data)
      resolve({ success: true })
    }, 1000)
  })
}

const mockRestoreVersion = (id: number) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      console.log('恢复版本:', id)
      resolve({ success: true })
    }, 1000)
  })
}

const mockDeleteVersion = (id: number) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      console.log('删除版本:', id)
      resolve({ success: true })
    }, 1000)
  })
}
</script>

<style scoped>
.version-management {
  max-height: 70vh;
  overflow-y: auto;
}

.current-version-card,
.version-history-card {
  margin-bottom: 20px;
  border: 1px solid #ebeef5;
}

.current-version-card:last-child,
.version-history-card:last-child {
  margin-bottom: 0;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.header-actions {
  display: flex;
  gap: 8px;
}

.current-version-info {
  padding: 10px 0;
}

.version-item {
  margin-bottom: 15px;
  display: flex;
  align-items: center;
}

.version-item:last-child {
  margin-bottom: 0;
}

.version-item label {
  font-weight: 500;
  color: #606266;
  min-width: 80px;
  margin-right: 10px;
}

.version-number {
  font-weight: 600;
  color: #409eff;
}

.version-description {
  margin-top: 15px;
}

.version-description label {
  font-weight: 500;
  color: #606266;
  display: block;
  margin-bottom: 8px;
}

.version-description p {
  margin: 0;
  color: #303133;
  line-height: 1.6;
}

.form-tip {
  font-size: 12px;
  color: #909399;
  margin-left: 10px;
}

.version-detail {
  padding: 10px 0;
}

.content-preview {
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
  border: 1px solid #ebeef5;
  max-height: 300px;
  overflow-y: auto;
  white-space: pre-wrap;
  line-height: 1.6;
}

.version-compare {
  padding: 10px 0;
}

.compare-header {
  margin-bottom: 20px;
}

.compare-panel {
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 15px;
}

.compare-panel h4 {
  margin: 0 0 15px 0;
  color: #303133;
  font-size: 16px;
  font-weight: 600;
}

.content-diff {
  background-color: #f5f7fa;
  padding: 15px;
  border-radius: 4px;
  min-height: 200px;
  max-height: 400px;
  overflow-y: auto;
  white-space: pre-wrap;
  line-height: 1.6;
}

.dialog-footer {
  text-align: right;
}

:deep(.el-card__header) {
  padding: 15px 20px;
  border-bottom: 1px solid #ebeef5;
  background-color: #fafafa;
}

:deep(.el-card__body) {
  padding: 20px;
}

:deep(.el-table) {
  font-size: 14px;
}

:deep(.el-table .cell) {
  padding: 0 8px;
}

:deep(.el-descriptions__label) {
  font-weight: 500;
}
</style>